package com.github.byakkili.bim.cluster.redisson;

import cn.hutool.core.util.ObjectUtil;
import com.github.byakkili.bim.core.cluster.AbstractClusterManager;
import com.github.byakkili.bim.core.cluster.BaseClusterPacket;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;

/**
 * @author Guannian Li
 */
@Slf4j
public class RedissonClusterManager extends AbstractClusterManager {

    private RTopic rTopic;

    public RedissonClusterManager(RTopic rTopic) {
        this.rTopic = rTopic;
        this.rTopic.addListener(BaseClusterPacket.class, (channel, msg) -> {
            if (ObjectUtil.notEqual(getContext().getServerId(), msg.getFromServerId())) {
                if (log.isDebugEnabled()) {
                    log.debug("Receive cluster packet: {}", msg);
                }
                doReceive(msg);
            }
        });
    }

    @Override
    protected boolean doSend(BaseClusterPacket clusterPacket) {
        long clientNumber = rTopic.publish(clusterPacket);
        if (log.isDebugEnabled()) {
            log.debug("Send to cluster, client: {}", clientNumber);
        }
        return true;
    }
}
